package command

import (
	"pan/api"
	"pan/common/log"
)

type LoginCommand struct {
	user     string
	password string
}

func (l *LoginCommand) Run(opts []*Option, args []string) {
	if !l.parseOption(opts) {
		return
	}
	log.Debug("user:", l.user, ", password:", l.password)

	_, err := api.LoginApi(&api.LoginRequest{Account: l.user, Password: l.password})
	if err != nil {
		panic(err)
	}
	log.Info("login success")
}

func (l *LoginCommand) parseOption(opts []*Option) bool {
	for _, opt := range opts {
		switch opt.Name {
		case "user":
			l.user = opt.StrValue
		case "password":
			l.password = opt.StrValue
		}
	}
	if l.user == "" || l.password == "" {
		log.Error("need username and password")
		return false
	}
	return true
}

func (l *LoginCommand) Description() string {
	return "Standard login by username and password"
}

func (l *LoginCommand) Arguments() []Argument {
	return nil
}

func (l *LoginCommand) Options() []*Option {
	return []*Option{
		{
			ShortName:    "u",
			Name:         "user",
			Description:  "login username",
			OptType:      StrOption,
			DefaultValue: "",
		},
		{
			ShortName:    "p",
			Name:         "password",
			Description:  "login password",
			OptType:      StrOption,
			DefaultValue: "",
		},
	}
}

func NewLoginCommand() *LoginCommand {
	return &LoginCommand{}
}
